let logger = require("pomelo-logger").getLogger(__filename);
let DateUtil = require("../../../../utils/dateUtil");
let COMPONENT_NAME = "permissionComponent";

PermissionComponent = function (owner) {
    this.owner = owner;
    this.enabled = true;
    this.disableReason = "";
    this.disableTime = 0;
};

PermissionComponent.prototype.isEnabled = function () {
    return this.enabled;
};

PermissionComponent.prototype.getDisableReason = function () {
    return this.disableReason;
};

PermissionComponent.prototype.getDisableTime = function () {
    return this.disableTime;
};

PermissionComponent.prototype.disable = function (reason) {
    if(!!reason){
        this.enabled = false;
        this.disableReason = reason;
        this.disableTime = DateUtil.nowMS();
        return true;
    }
    return false;
};

PermissionComponent.prototype.enable = function () {
    this.enabled = true;
    this.disableReason = "";
    this.disableTime = 0;
};

PermissionComponent.prototype.fromBSON = function (document) {
    if (!document.hasOwnProperty(COMPONENT_NAME)) {
        logger.error("load permissionComponent failed. document=" + JSON.stringify(document));
        return;
    }
    let root = document[COMPONENT_NAME];
    this.enabled = root["enabled"];
    this.disableReason = root["disableReason"];
    this.disableTime = root["disableTime"];
};

PermissionComponent.prototype.buildBSON = function (document) {
   document[COMPONENT_NAME] = {
       enabled: this.enabled,
       disableReason: this.disableReason,
       disableTime: this.disableTime
   };
};

PermissionComponent.prototype.toJSON = function () {
    return {
        enabled : this.enabled,
        disableReason : this.disableReason,
        disableTime : this.disableTime
    };
};

module.exports.create = function (owner) {
    return new PermissionComponent(owner);
};
